<?php namespace App\Models;

use bright_tech\laravel\aliyun_oss\AliyunOssService;
use Carbon\Carbon;
use Symfony\Component\HttpFoundation\File\Exception\FileException;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Auth;
use Illuminate\Database\Eloquent\Model;
use Storage;
use Image;
use App\Services\AliyunOss;
use App\Models\Works;
use Illuminate\Database\Eloquent\SoftDeletes;

/**
 * Class WorksUpload
 *
 * @package App\Models
 * @property int $id
 * @property int $user_id 用户id
 * @property int $works_id 作品id
 * @property string $filename
 * @property string $path
 * @property int $size
 * @property int $upload_id
 * @property string $extension
 * @property string $mime_type
 * @property string $created_at
 * @property string $updated_at
 * @property string $disk
 * @property string $key
 * @property string $thumb
 * @property string $converted_video 转换后的视频
 * @property-read \User $user
 *
 * @mixin \Eloquent
 */
class WorksUpload extends Model
{
    use SoftDeletes;
    /**
     * 允许上传的文件类型(mime type)
     * @var array
     */
    public $uploadFileTypes = [
        'image/png',
        'image/gif',
        'image/jpg',
        'image/jpeg',
        'video/x-msvideo',
        'audio/x-ms-wmv',
        'video/x-ms-asf',
        'audio/mpeg',
        'video/mp4',
        'video/x-flv',
        'image/tiff',
        'application/pdf',
        'application/msword',
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'application/x-shockwave-flash',
        'text/plain',
        'application/vnd.openxmlformats-officedocument.presentationml.presentation',
        'application/vnd.ms-powerpoint',
        'application/zip',
    ];


    /**
     * 允许上传的文件后缀名
     * @var array
     */
    public $uploadFileExtensions;

    /**
     * Get the uploads owner.
     *
     * @return User
     */
    public function user()
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    /**
     * Get the uploads works.
     *
     * @return Works
     */
    public function works()
    {
        return $this->belongsTo(Works::class , 'works_id');
    }

    /**
     * @deprecated
     * @param UploadedFile $file
     */
//    public function process(UploadedFile $file)
//    {
//        // File extension
//        $this->extension = $file->getClientOriginalExtension();
//        // Mimetype for the file
//        $this->mime_type = $file->getMimeType();
//        // Current user or 0
//        $this->user_id = (Auth::user() ? Auth::user()->id : 0);
//
//        $this->size = $file->getSize();
//
//        $this->upload($file);
//
//        $this->path = $this->key;
//        $this->filename = basename($this->key);
//
//        $this->save();
//
//    }

    /**
     * @deprecated
     * @param UploadedFile $file
     */
//    public function upload(UploadedFile &$file)
//    {
//        // Check the upload type is valid by extension and mimetype
//        $this->verifyUploadType($file);
//
//        // Check file size
//
//        // Check to see if file exists already. If so append a random string.
//        $this->resolveKeyName();
//
//        // Upload the file to the folder. Exception thrown from move.
//        if (!Storage::disk($this->disk)->put($this->key, File::get($file))) {
//            throw new FileException('保存文件失败.');
//        }
//    }

    /**
     * 校验上传文件类型
     * @param UploadedFile $file
     * @deprecated
     */
//    public function verifyUploadType(UploadedFile $file)
//    {
//        if (!in_array($file->getMimeType(), $this->uploadFileTypes) ||
//            !in_array(strtolower($file->getClientOriginalExtension()), $this->uploadFileExtensions)
//        ) {
//            throw new FileException('文件类型有误.');
//        }
//    }

    /**
     * @deprecated
     */
//    public function resolveKeyName()
//    {
//        //构建文件名
//        if (!isset($this->key)) {
//            $this->key = md5(uniqid(mt_rand(), true)) . ($this->extension ? '.' . $this->extension : '');
//        }
//
//        // If file exists append string and try again.
//        if (Storage::disk($this->disk)->exists($this->key)) {
//            // Default file postfix
//            $i = '01';
//
//            // Get the file bits
//            $basename = basename($this->key, ($this->extension ? '.' . $this->extension : null));
//
//            $basenamePieces = explode('_', $basename);
//
//            // If there's more than one piece then let see if it's our counter.
//            if (count($basenamePieces) > 1) {
//                // Pop the last part of the array off.
//                $last = array_pop($basenamePieces);
//                // Check to see if the last piece is an int. Must be 2 long. This isn't the best, but it'll do in most cases.
//                if (strlen($last) == 2 && (is_int($last) || ctype_digit($last))) {
//                    // Add one, which converts this string to an int. Gotta love PHP ;)
//                    $last += 1;
//                    // Prepare to add the proper amount of 0's in front
//                    $b = 2 - strlen($last);
//                    $i = $last;
//                    for ($c = 1; $c <= $b; $c++) {
//                        $i = '0' . $i;
//                    }
//                } else {
//                    // Put last back on the array
//                    array_push($basenamePieces, $last);
//                }
//                // Put the pieces back together without the postfix.
//                $basename = implode('_', $basenamePieces);
//            }
//
//            // Create the filename
//            $this->key = $basename . '_' . $i . '.' . $this->extension;
//            $this->resolveKeyName();
//        }
//    }

    /**
     * @param UploadedFile $file
     * @return string
     *
     * @deprecated
     */
//    public function getBasename(UploadedFile $file)
//    {
//        // Get the file bits
//        $basename = basename((isset($file->fileSystemName) ? $file->fileSystemName : $file->getClientOriginalName()), $file->getClientOriginalExtension());
//        // Remove trailing period
//        return (substr($basename, -1) == '.' ? substr($basename, 0, strlen($basename) - 1) : $basename);
//    }

    /**
     * 删除文件
     *
     * @deprecated
     */
//    public function deleteFile()
//    {
//        Storage::disk($this->disk)->delete($this->key);
//    }

    /**
     * 检查联网状态，判定线上线下模式
     */
    public function checkOnlineStatus()
    {
        return Setting::where('name' , 'online')->first()->value;
    }

    /**
     * 获取原文件访问ur【原图】
     * 访问URL和上传URL可能不同,访问URL可能使用CDN
     * @return string
     */
    public function getFileUrl()
    {
        if ($this->checkOnlineStatus()){
            $app = app();
            $aliyun = $app->make(AliyunOssService::class);
            return $aliyun->getOssUtilities()->getFileViewEndpoint() . '/' . $this->key;
        }else{
            return asset('works/uploads/'.$this->path);
        }

    }


    /**
     * 获取原视频访问ur【原图】
     * 访问URL和上传URL可能不同,访问URL可能使用CDN
     * @return string
     */
    public function getVideoUrl()
    {
        $filename = pathinfo($this->key, PATHINFO_FILENAME);
        $path = pathinfo($this->key , PATHINFO_DIRNAME) . '/' . $filename . '_transcode.mp4';
        if ($this->checkOnlineStatus()){
            $app = app();
            $aliyun = $app->make(AliyunOssService::class);
            return $aliyun->getOssUtilities()->getFileViewEndpoint() . '/' . $path;
        }else{
            return asset('works/uploads/'.$path);
        }

    }

    /**
     * 获取原视频封面访问ur【原图】
     * 访问URL和上传URL可能不同,访问URL可能使用CDN
     * @return string
     */
    public function getVideoCoverUrl()
    {
        $filename = pathinfo($this->key, PATHINFO_FILENAME);
        $path = pathinfo($this->key , PATHINFO_DIRNAME) . '/' . $filename . '_cover.jpg';
        if ($this->checkOnlineStatus()){
            $app = app();
            $aliyun = $app->make(AliyunOssService::class);
            return $aliyun->getOssUtilities()->getFileViewEndpoint() . '/' . $path;
        }else{
            return asset('works/uploads/'.$path);
        }

    }

    /**
     * 获取原视频封面访问ur【原图】
     * 访问URL和上传URL可能不同,访问URL可能使用CDN
     * @return string
     */
    public function getVideoThumbUrl()
    {
        $filename = pathinfo($this->key, PATHINFO_FILENAME);
        $path = pathinfo($this->key , PATHINFO_DIRNAME) . '/' . $filename . '_cover.jpg';
        if ($this->checkOnlineStatus()){
            $app = app();
            $aliyun = $app->make(AliyunOssService::class);
            return $aliyun->getOssUtilities()->getImageViewEndpoint() . '/' . $path . '@600w_1l';
        }else{
            return asset('works/uploads/'.pathinfo($this->key , PATHINFO_DIRNAME) . '/' . $filename . '_thumb.jpg');
        }

    }

    /**
     * 获取缩略图地址【最小尺寸图片】
     *
     * @return string
     */
    public function getThumbnailUrl()
    {
        $app = app();
        $aliyun = $app->make(AliyunOssService::class);
        if ($this->getFileType() == 'image') {
            $host = $aliyun->getOssUtilities()->getImageViewEndpoint();
            return $host . '/' . $this->path . '@111h_78w_2e';
        } else {
            return '';
        }
    }

    /**
     * 获取评审图地址【中等尺寸图片】
     * @return string
     */
    public function getRateUrl()
    {
        if ($this->checkOnlineStatus()) {
            $app = app();
            $aliyun = $app->make(AliyunOssService::class);
            if ($this->getFileType() == 'image') {
                $host = $aliyun->getOssUtilities()->getImageViewEndpoint();
                return $host . '/' . $this->path . '@600w_1l';
            } else {
                return '';
            }
        }else{
            return asset('works/uploads/'. pathinfo($this->key , PATHINFO_DIRNAME) . '/' . pathinfo($this->key , PATHINFO_FILENAME) . '_rate' . '.' . $this->extension);
        }
    }

    /**
     * 获取评审缩略图地址 【小尺寸图片】
     * @return string
     */
    public function getRateThumbUrl()
    {
        if ($this->checkOnlineStatus()) {
            $app = app();
            $aliyun = $app->make(AliyunOssService::class);
            if ($this->getFileType() == 'image') {
                $host = $aliyun->getOssUtilities()->getImageViewEndpoint();
                return $host . '/' . $this->path . '@200h_200w_2e';
            } else {
                return '';
            }
        }else{
            return asset('works/uploads/'. pathinfo($this->key , PATHINFO_DIRNAME) . '/' . pathinfo($this->key , PATHINFO_FILENAME) . '_rateThumb' . '.' . $this->extension);
        }
    }

    /**
     * 获取缩略图网址
     * @return bool|string
     * @deprecated
     */
//    public function getThumbUrl()
//    {
//        if ($this->thumb) {
//            return url($this->thumb);
//        } elseif (in_array(strtolower($this->extension), ['jpg', 'jpeg', 'png', 'gif'])) {
//            return $this->generateThumb();
//        } else {
//            return url('assets/thumb/' . strtolower($this->extension) . '.png');
//        }
//    }

    /**
     * 生成缩略图
     * @param int $width
     * @return bool|string
     * @deprecated
     */
//    public function generateThumb($width = 600)
//    {
//        try {
//            if (in_array($this->mime_type, ['image/png', 'image/gif', 'image/jpg', 'image/jpeg'])) {
//                $this->thumb = 'uploads/thumbs/' . $this->filename;
//                $img = Image::make(Storage::disk($this->disk)->get($this->key))->widen(intval($width));
//                $img->save(public_path($this->thumb));
//            } else {
//                $this->thumb = 'assets/thumb/' . $this->extension . '.png';
//            }
//            $this->save();
//            return url($this->thumb);
//        } catch (\Exception $e) {
//            \Log::error('生成缩略图失败.' . $e->getMessage(), $this->toArray());
//        }
//
//        return false;
//    }

    /**
     * 获取文件分类
     *
     * @return string
     */
    public function getFileType()
    {
        $type = 'undefined';


//        'application/pdf',
//        'application/msword',
//        'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
//        'application/x-shockwave-flash',
//        'text/plain',
//        'application/vnd.openxmlformats-officedocument.presentationml.presentation',
//        'application/vnd.ms-powerpoint',
//        'application/zip',
        switch ($this->mime_type) {
            case 'image/png':
            case 'image/gif':
            case 'image/jpg':
            case 'image/jpeg':
            case 'image/tiff':
                $type = 'image';
                break;
            case 'video/x-msvideo':
            case 'video/x-ms-asf':
            case 'video/mp4':
            case 'video/x-flv':
                $type = 'video';
                break;
            case 'audio/x-ms-wmv':
            case 'audio/mpeg':
                $type = 'audio';
                break;


        }
        return $type;
    }

    /**
     * 是否为图片格式
     * @deprecated
     * @return bool
     */
//    public function isImage()
//    {
//        if (in_array($this->extension, ['jpg', 'jpeg', 'gif', 'png'])) {
//            return true;
//        } else {
//            return false;
//        }
//    }

    /**
     * 是否为视频格式
     * @return bool
     * @deprecated
     */
//    public function isVideo()
//    {
//        if (in_array($this->extension, ['avi', 'wmv', 'mp4', 'flv'])) {
//            return true;
//        } else {
//            return false;
//        }
//    }

    /**
     * 视频播放html
     * @return string
     */
    public function getPlayHtml()
    {
        if ($this->converted_video) {
            return '<video src="' . url($this->converted_video) . '" controls="controls"></video>';
        } elseif ($this->extension == 'mp4') {
            return '<video src="' . $this->getFileUrl() . '" controls="controls"></video>';
        } else {
            return '<h3>不支持在线播放</h3>';
        }
    }

    /**
     * 获取碱法投票用缩略图网址
     * @return bool|string
     */
    public function getJianfaThumbUrl()
    {
        return @file_get_contents('http://www.adshangchuan.com/jianfa/works-upload-thumb/' . $this->id);
        /*if ($this->thumb) {
            $url= url($this->thumb);
        } elseif (in_array($this->extension, ['jpg', 'jpeg', 'png', 'gif'])) {
            $url= $this->generateThumb();
        } else {
            $url= url('assets/thumb/' . strtolower($this->extension) . '.png');
        }

        $url = str_replace(url(), env('APP_URL'), $url);
        return $url;*/
    }

    /**
     * 生成显示的html
     * @return string
     */
    public function getDisplayHtml()
    {
        if ($this->extension == 'gif') {
            return '<p><img src="' . $this->getFileUrl() . '" style="max-width: 800px;"></p>';
        } elseif ($this->extension == 'swf') {
            return '<p>
                        <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
                                codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0"
                                width="600" height="400" id="simplevideostreaming" align="middle">
                            <param name="allowScriptAccess" value="sameDomain"/>
                            <param name="allowFullScreen" value="true"/>
                            <param name="movie" value="{{ $workUpload->getFileUrl() }}"/>
                            <param name="quality" value="high"/>
                            <param name="bgcolor" value="#000000"/>
                            <embed src="' . $this->getFileUrl() . '" quality="high" bgcolor="#000000"
                                   width="600" height="400" name="simplevideostreaming" align="middle"
                                   allowScriptAccess="sameDomain" allowFullScreen="true"
                                   type="application/x-shockwave-flash"
                                   pluginspage="http://www.macromedia.com/go/getflashplayer"></embed>
                        </object>
                    </p>';
        } elseif ($this->isVideo()) {
            return $this->getPlayHtml() . '<p><img src="' . $this->getThumbUrl() . '" style="max-width: 640px;"></p>';
        } else {
            return '<p><a href="' . $this->getFileUrl() . '" target="_blank">
                                <img src="' . $this->getThumbUrl() . '">
                            </a></p>';
        }
    }


}